package cn.mw.cmdb.template.utils;

import cn.mw.cmdb.template.param.TemplateQueryParam;
import cn.mw.components.mongodb.entity.SearchParam;
import cn.mw.microMonitorCommon.util.ListMapObjUtils;
import com.google.common.base.Strings;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

import static cn.mw.cmdb.util.ListSortUtil.compareValues;

/**
 * @description 模板功能排序工具
 */
public class TemplateSortUtil {

    public static String ascSortTag = "ASC";

    public static List templateSortList(List data, SearchParam searchParam,TemplateQueryParam param) {
        if(data == null){
            return new ArrayList();
        }
        List list = ListMapObjUtils.objectsToMaps(data);
        if(param != null){
            list = dataFilter(list,param);
        }
        if (searchParam != null && !Strings.isNullOrEmpty(searchParam.getSortName())) {
            String sortName = searchParam.getSortName();
            String sortOrder = searchParam.getSortOrder();
            boolean ASC_order = (ascSortTag.equals(sortOrder));
            // 对指定字段进行排序，为空或null的排在最后
            Collections.sort(list, new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> m1, Map<String, Object> m2) {
                    Object value1 = m1.get(sortName);
                    Object value2 = m2.get(sortName);
                    return compareValues(value1, value2, ASC_order);
                }
            });
            return list;
        }
        return list;
    }


    private static List dataFilter(List<Map> realData, TemplateQueryParam param){
        if(CollectionUtils.isEmpty(realData) || StringUtils.isEmpty(param.getQueryKey()) || StringUtils.isEmpty(param.getQueryValue())){
            return realData;
        }
        List newRealData = realData.stream().filter(item -> String.valueOf(item.get(param.getQueryKey())).toLowerCase().contains(param.getQueryValue().toLowerCase())).collect(Collectors.toList());
        return newRealData;
    }
}
